package cn.rkylin.oms.sysOrder.service;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.CodeUtil;
import cn.rkylin.oms.common.utils.DateUtil;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.item.domain.SkuGroup;
import cn.rkylin.oms.item.vo.SkuVO;
import cn.rkylin.oms.order.domain.EcOrder;
import cn.rkylin.oms.order.domain.EcTrade;
import cn.rkylin.oms.order.service.IOrderService;
import cn.rkylin.oms.sysOrder.dao.ISysOrderDAO;
import cn.rkylin.oms.sysOrder.domain.SysOrder;
import cn.rkylin.oms.sysOrder.domain.SysOrderGoods;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 创建系统订单
 *
 * @author wangxing
 * @version 1.0
 * @created 2017.09.14
 */
@Service("createSysOrderService")
public class CreateSysOrderService {
    //    private static final Log logger = LogFactory.getLog(SysOrderController.class);
    //    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    //待进系统的平台订单数据集
//    private List<EcTrade> tradeList = null;
    //订单主表与明细表关联关系map
//    private Map<String, List<EcOrder>> tradeOrderMap = null;
    //订单商品明细表与平台商品表关联关系map
//    private Map<String, List<SkuVO>> orderItemSkuMap = null;
    //平台商品与组合商品关联关系map
//    private Map<String, List<SkuGroup>> itemSkuGrouprMap = null;

    @Autowired
    private ISysOrderDAO sysOrderDAO;//系统订单数据层

    @Autowired
    private IOrderService orderService;//平台订单服务层

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 创建系统订单
     *
     * @param shopVO
     * @param buyerNick 买家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @throws Exception
     */
    public void createSysOrder(ShopVO shopVO, String buyerNick, String tradeCode) throws Exception {
        String strShopId = shopVO.getShopId();
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单进系统开始---------------------------------------"));
        //企业Id
        String strEntId = shopVO.getEntId();
        //是否允许自动合并订单
        String strIsAutoMergeOrder = shopVO.getIsAutoMergeOrder();
        //项目简称
        String strPrjShortName = shopVO.getPrjShortName();
        //获取待进系统平台订单入参
        Map<String, String> tradeMap = new HashMap();
        tradeMap.put("shopId", strShopId);

        tradeMap.put("storType", shopVO.getStorType());

        String sTime = DateUtil.formatDate(shopVO.getStartTime());
        tradeMap.put("startTime", sTime);
        String eTime = DateUtil.formatDate(shopVO.getExpireTime());
        tradeMap.put("endTime", eTime);
        if (StringUtils.isNotBlank(tradeCode)) {
            tradeMap.put("ecTradeCode", tradeCode);
        }
        if (StringUtils.isNotBlank(buyerNick)) {
            tradeMap.put("ecCustCode", buyerNick);
        }

        //待进系统的平台订单数据集
        List<EcTrade> tradeList = new ArrayList<EcTrade>();
        //订单主表与明细表关联关系map
        Map<String, List<EcOrder>> tradeOrderMap = new HashMap();
        //订单商品明细表与平台商品表关联关系map
        Map<String, List<SkuVO>> orderItemSkuMap = new HashMap();
        //平台商品与组合商品关联关系map
        Map<String, List<SkuGroup>> itemSkuGrouprMap = new HashMap();


//1.1、获取待进系统的平台订单数据集------------------------------------------------------------------------------------------
        tradeList = getTradeList(tradeMap, strShopId);
        if (tradeList != null && tradeList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单数为:" + String.valueOf(tradeList.size())));
//---------------------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取网店默认仓库和项目默认物流开始"));
            String strStorId = "";
            String strStorName = "";
            String strStorCode = "";
            String strLgstId = "";
            String strLgstName = "";
            String strLgstCode = "";
//调用OMS 仓库controller获取当前网店下仓库及覆盖区域信息 (覆盖区域本期暂不考虑,仅取默认仓库)
            Map<String, Object> resultMapStor = getOmsRequestMap(omsUrl + "stor/getDefaultStor.action", "shopId=" + strShopId, strShopId);
            if (resultMapStor != null && resultMapStor.size() > 0) {
                strStorId = resultMapStor.get("storId").toString();
                strStorName = resultMapStor.get("storName").toString();
                strStorCode = resultMapStor.get("storCode").toString();
            }
//调用OMS 物流公司controller获取物流公司及覆盖区域信息 (覆盖区域本期暂不考虑,仅取默认物流公司)
            if ("f3ad66a3d24446d8a0f34860070e3b0b".equals(strShopId.toLowerCase())) {
                // 店铺 SKT电子烟旗舰店 指定  无界中通  物流
                strLgstId = "c2a16a07fdd244e8b0a3d7cc296eee66";
                strLgstName = "无界中通";
                strLgstCode = "JDZTO";
            } else {
                Map<String, Object> resultMapLgst = getOmsRequestMap(omsUrl + "lgst/getDefaultLgst.action", "prjId=" + shopVO.getPrjId(), strShopId);
                if (resultMapLgst != null && resultMapLgst.size() > 0) {
                    strLgstId = resultMapLgst.get("lgstId").toString();
                    strLgstName = resultMapLgst.get("lgstName").toString();
                    strLgstCode = resultMapLgst.get("lgstCode").toString();
                }
            }

//---------------------------------------------------------------------------------------------------------
//1.2、获取订单主表与明细表关联关系map，并返回平台商品入参Map--------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单商品开始"));
            Map<String, Object> itemSkuMap = new HashMap();
            tradeOrderMap = getTradeOrderMap(strShopId, tradeList, itemSkuMap);
//1.3、获取订单商品明细表与平台商品表关联关系map，并返回组合商品入参Map--------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取平台商品开始---------------------"));
            Map<String, Object> skuGroupMap = new HashMap();
            orderItemSkuMap = getOrderItemSkuMap(itemSkuMap, skuGroupMap);
//1.4、获取平台商品与组合商品关联关系map--------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取平台商品组合商品开始---------------------"));
            itemSkuGrouprMap = getItemSkuGrouprMap(skuGroupMap);
//1.5、循环平台订单tradeList逐条处理订单信息以及对应商品信息，包括仓库、物流等信息...-----------------------------------------------------
            EcTrade ecTrade = new EcTrade();
            SysOrder sysOrder = new SysOrder();
            int iRes = 0;
            for (int tradeIndex = 0; tradeIndex < tradeList.size(); tradeIndex++) {
                iRes = 0;
                ecTrade = tradeList.get(tradeIndex);
                logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "平台交易号" + ecTrade.getEcTradeCode() + "进系统开始*******************"));
                logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "进系统开始*******************"));

                sysOrder = setSysOrderInfo(ecTrade, strEntId, strIsAutoMergeOrder, strPrjShortName, strStorId, strStorName,
                        strLgstId, strLgstName, strStorCode, strLgstCode, tradeOrderMap, orderItemSkuMap, itemSkuGrouprMap);
                logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "平台交易号" + ecTrade.getEcTradeCode() + "赋值阶段结束*******************"));
                logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "赋值阶段结束*******************"));
//1.6、开始逐条订单插入到数据库-----------------------------------------------------------------------------------
                if (sysOrder != null) {
                    iRes = insertSysOrderInfo(sysOrder);
                    logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "平台交易号" + ecTrade.getEcTradeCode() + "插入数据库阶段结束*******************"));
                    logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "插入数据库阶段结束*******************"));
                }
//1.7、开始逐条订单更新插入状态-----------------------------------------------------------------------------------
                if (iRes > 0) {
                    updateEcTradeInsertStatus(ecTrade.getEcTradeId(), ecTrade.getEcTradeCode());
                    logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "平台交易号" + ecTrade.getEcTradeCode() + "更新平台订单进系统标识阶段结束*******************"));
                    logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "更新平台订单进系统标识阶段结束*******************"));
                }
                logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "平台交易号" + ecTrade.getEcTradeCode() + "进系统结束*******************"));
                logUtil.info(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "进系统结束*******************"));
            }
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单数为:0"));
        }
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单进系统结束---------------------------------------"));
    }

    /**
     * 调用OMS工程 Get方式
     *
     * @param requestUrl    请求地址
     * @param requestParams 请求参数拼接
     * @return
     * @throws Exception
     */
    private Map<String, Object> getOmsRequestMap(String requestUrl, String requestParams, String strShopId) throws Exception {
        Map<String, Object> resultMap = null;
        try {
            // 请求数据
            String resJson = HttpUtils.sendByGet(requestUrl, requestParams);
            // 转换响应数据
            Map<String, Object> resultJsonMap = JSON.parseObject(resJson, Map.class);
            if (resultJsonMap != null && resultJsonMap.size() > 0) {
                if (resultJsonMap.containsKey("result")
                        && "success".equals(resultJsonMap.get("result"))) {
                    resultMap = resultJsonMap;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取默认仓库，物流公司异常:" + ex.getMessage()));
        }
        return resultMap;
    }

    /**
     * 获取待进系统的平台订单数据集
     *
     * @param reqMap
     * @throws Exception
     */
    private List<EcTrade> getTradeList(Map<String, String> reqMap, String strShopId) throws Exception {
        List<EcTrade> tradeList = new ArrayList<EcTrade>();
        try {
            if (reqMap != null && reqMap.size() > 0) {
                tradeList = orderService.selectTradeList(reqMap);
                if (tradeList != null && tradeList.size() > 0) {
                    //接口表订单平台交易号累加拼串，用于获取系统订单入参
                    List<String> tradeCodeAddList = new ArrayList<String>();
                    for (int tradeIndex = 0; tradeIndex < tradeList.size(); tradeIndex++) {
                        tradeCodeAddList.add(tradeList.get(tradeIndex).getEcTradeCode());
                    }
                    Map<String, Object> TradeCodeAddMap = new HashMap();
                    TradeCodeAddMap.put("trade_code", tradeCodeAddList);

                    //获取系统订单数据集，用于判断当前接口表订单是否已经存在于系统订单中
                    List<String> sysOrderExistsList = sysOrderDAO.selectSysOrderListByTradeCode(TradeCodeAddMap);
                    if (sysOrderExistsList != null && sysOrderExistsList.size() > 0) {
                        //过滤掉已存在的系统订单
                        String strTradeCode = "";
                        for (int tradeIndex = tradeList.size() - 1; tradeIndex >= 0; tradeIndex--) {
                            strTradeCode = tradeList.get(tradeIndex).getEcTradeCode();
                            if (sysOrderExistsList.contains(strTradeCode)) {
                                tradeList.remove(tradeIndex);
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
//            ex.printStackTrace();
            tradeList = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单异常:" + ex.getMessage()));
        }
        return tradeList;
    }

    /**
     * 获取订单主表与明细表关联关系map，并返回平台商品入参Map
     *
     * @return
     * @throws Exception
     */
    private Map<String, List<EcOrder>> getTradeOrderMap(String strShopId, List<EcTrade> tradeList, Map<String, Object> itemSkuMap) throws Exception {
        Map<String, List<EcOrder>> tradeOrderMap = new HashMap();
        try {
            Map<String, Object> TradeIdAddMap = new HashMap();
            if (tradeList != null && tradeList.size() > 0) {
                //接口表订单Id累加拼串，用于获取订单商品明细入参
                List<String> tradeIdAddList = new ArrayList<String>();
                for (int i = 0; i < tradeList.size(); i++) {
                    tradeIdAddList.add(tradeList.get(i).getEcTradeId());
                }
                TradeIdAddMap.put("trade_id", tradeIdAddList);
            } else {
                tradeOrderMap = null;
                itemSkuMap = null;
                logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单商品异常:主单据数量为0"));
                return tradeOrderMap;
            }

            //获取订单商品明细数据集
            List<EcOrder> orderAllList = orderService.selectTradeOrderList(TradeIdAddMap);
            if (orderAllList != null && orderAllList.size() > 0) {
                //--------------------------------------------------------------------------------------
                //订单主表id
                String strEcTradeId = "";
                //订单商品明细列表
                List<EcOrder> orderList = new ArrayList<EcOrder>();
                //订单明细实体
                EcOrder ecOrder = new EcOrder();
                //--------------------------------------------------------------------------------------
                //接口表订单商品明细ec_item_code累加拼串，用于获取订单商品明细对应平台商品入参
                List<String> itemCodeAddList = new ArrayList<String>();
                //接口表订单商品明细ec_sku_code累加拼串，用于获取订单商品明细对应平台商品入参
                List<String> skuCodeAddList = new ArrayList<String>();
                //--------------------------------------------------------------------------------------
                //循环订单商品明细匹配其与订单关系Map，并拼串对应平台商品入参信息
                for (int orderIndex = 0; orderIndex < orderAllList.size(); orderIndex++) {
                    //--------------------------------------------------------------------------------------
                    ecOrder = orderAllList.get(orderIndex);
                    strEcTradeId = ecOrder.getEcTradeId();
                    if (tradeOrderMap.get(strEcTradeId) != null) {
                        orderList = tradeOrderMap.get(strEcTradeId);
                    } else {
                        orderList = new ArrayList<EcOrder>();
                    }
                    //累加订单商品明细
                    orderList.add(ecOrder);
                    tradeOrderMap.put(strEcTradeId, orderList);
                    //--------------------------------------------------------------------------------------
                    //拼串对应订单商品明细中的 ItemCode、SkuCode
                    itemCodeAddList.add(orderAllList.get(orderIndex).getEcItemCode());
                    skuCodeAddList.add(orderAllList.get(orderIndex).getEcSkuCode());
                }
                //获取平台商品所需入参
//                Map<String, Object> ecSkuMap = new HashMap();
//                ecSkuMap.put("ItemCode", itemCodeAddList);
//                ecSkuMap.put("SkuCode", skuCodeAddList);
//                itemSkuMap = ecSkuMap;
                itemSkuMap.put("ItemCode", itemCodeAddList);
                itemSkuMap.put("SkuCode", skuCodeAddList);
            }
        } catch (Exception ex) {
//            ex.printStackTrace();
            tradeOrderMap = null;
            itemSkuMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待进系统平台订单商品异常:" + ex.getMessage()));
        }
        return tradeOrderMap;
    }

    /**
     * 获取订单商品明细表与平台商品表关联关系map，并返回组合商品入参Map
     *
     * @param map
     * @return
     * @throws Exception
     */
    private Map<String, List<SkuVO>> getOrderItemSkuMap(Map<String, Object> map, Map<String, Object> skuGroupMap) throws Exception {
        Map<String, List<SkuVO>> orderItemSkuMap = new HashMap();
//        Map<String, Object> returnMap = null;
        try {
            if (map != null && map.size() > 0) {
                //获取订单商品明细对应平台商品信息数据集
                List<SkuVO> itemSkuList = orderService.selectItemSkuList(map);
                if (itemSkuList != null && itemSkuList.size() > 0) {
                    //--------------------------------------------------------------------------------------
                    //订单商品对应平台商品id和平台规格id合并 作为主键Key
                    String strItemSkuId = "";
                    //平台商品列表
                    List<SkuVO> skuList = new ArrayList<SkuVO>();
                    //平台商品实体
                    SkuVO sku = new SkuVO();
                    //--------------------------------------------------------------------------------------
                    //接口表订单商品明细ec_sku_id累加拼串，用于获取订单商品明细对应平台商品组合商品入参
                    List<String> ecSkuIdAddList = new ArrayList<String>();
                    //--------------------------------------------------------------------------------------
                    //循环平台商品匹配其与订单商品关系Map，并拼串对应平台组合商品入参信息
                    for (int itemSkuIndex = 0; itemSkuIndex < itemSkuList.size(); itemSkuIndex++) {
                        //--------------------------------------------------------------------------------------
                        sku = itemSkuList.get(itemSkuIndex);
                        strItemSkuId = sku.getEcItemCode() + "-" + sku.getEcSkuCode();
                        if (orderItemSkuMap.get(strItemSkuId) != null) {
                            skuList = orderItemSkuMap.get(strItemSkuId);
                        } else {
                            skuList = new ArrayList<SkuVO>();
                        }
                        //累加平台商品
                        skuList.add(sku);
                        orderItemSkuMap.put(strItemSkuId, skuList);
                        //--------------------------------------------------------------------------------------
                        //拼串对应平台商品的 EcSkuId
                        if ("y".equals(sku.getIsGroup())
                                && !ecSkuIdAddList.contains(itemSkuList.get(itemSkuIndex).getEcSkuId())) {
                            ecSkuIdAddList.add(itemSkuList.get(itemSkuIndex).getEcSkuId());
                        }
                    }
                    //获取平台商品组合商品所需入参
//                    Map<String, Object> ecSkuGroupMap = new HashMap();
                    if (ecSkuIdAddList.size() > 0) {
                        skuGroupMap.put("EcSkuId", ecSkuIdAddList);
                    }
//                    returnMap = ecSkuGroupMap;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            orderItemSkuMap = null;
            skuGroupMap = null;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "获取待进系统平台订单平台商品异常:" + ex.getMessage()));
        }
        return orderItemSkuMap;
    }

    /**
     * 获取平台商品与组合商品关联关系map
     *
     * @param map
     * @throws Exception
     */
    private Map<String, List<SkuGroup>> getItemSkuGrouprMap(Map<String, Object> map) throws Exception {
        Map<String, List<SkuGroup>> itemSkuGrouprMap = new HashMap();
        try {
            if (map != null && map.size() > 0) {
                //获取订单商品明细对应平台商品组合商品信息数据集
                List<SkuGroup> itemSkuGroupList = orderService.selectItemSkuGroupList(map);
                if (itemSkuGroupList != null && itemSkuGroupList.size() > 0) {
                    //--------------------------------------------------------------------------------------
                    //Key
                    String strKey = "";
                    //组合商品列表
                    List<SkuGroup> skuGroupList = new ArrayList<SkuGroup>();
                    //组合商品实体
                    SkuGroup skuGroup = new SkuGroup();
                    //--------------------------------------------------------------------------------------
                    //循环组合商品匹配其与平台商品关系Map
                    for (int index = 0; index < itemSkuGroupList.size(); index++) {
                        //--------------------------------------------------------------------------------------
                        skuGroup = itemSkuGroupList.get(index);
                        strKey = skuGroup.getEcSkuId();
                        if (itemSkuGrouprMap.get(strKey) != null) {
                            skuGroupList = itemSkuGrouprMap.get(strKey);
                        } else {
                            skuGroupList = new ArrayList<SkuGroup>();
                        }
                        //累加组合商品
                        skuGroupList.add(skuGroup);
                        itemSkuGrouprMap.put(strKey, skuGroupList);
                        //--------------------------------------------------------------------------------------
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            itemSkuGrouprMap = null;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "获取待进系统平台订单商品组合商品异常:" + ex.getMessage()));
        }
        return itemSkuGrouprMap;
    }

    /**
     * 从平台订单映射出系统订单实例,待插入系统订单表准备
     *
     * @param ecTrade
     * @param strEntId
     * @param strIsAutoMergeOrder
     * @param strPrjShortName
     * @return
     * @throws Exception
     */
    private SysOrder setSysOrderInfo(EcTrade ecTrade, String strEntId, String strIsAutoMergeOrder,
                                     String strPrjShortName, String strStorId, String strStorName,
                                     String strLgstId, String strLgstName, String strStorCode, String strLgstCode,
                                     Map<String, List<EcOrder>> tradeOrderMap, Map<String, List<SkuVO>> orderItemSkuMap,
                                     Map<String, List<SkuGroup>> itemSkuGrouprMap) throws Exception {
        SysOrder sysOrder = new SysOrder();
        try {
            if (tradeOrderMap != null && tradeOrderMap.size() > 0
                    && orderItemSkuMap != null && orderItemSkuMap.size() > 0) {
                String strOrderId = SnoGerUtil.getUUID();
                sysOrder.setOrderId(strOrderId);
                sysOrder.setEntId(strEntId);
                sysOrder.setPrjId(ecTrade.getPrjId());
                sysOrder.setShopId(ecTrade.getShopId());
                sysOrder.setShopName(ecTrade.getShopName());
                sysOrder.setOrderCode("OR" + strPrjShortName + CodeUtil.getCode());
                sysOrder.setOrderTime(ecTrade.getOrderTime());
                sysOrder.setBuyerNick(ecTrade.getEcCustCode());
                sysOrder.setOrderType(ecTrade.getTradeType());//订单类型：担保交易，货到付款，见面交易，天猫国际
                sysOrder.setShopType(ecTrade.getShopType());
                sysOrder.setTradeStatus(ecTrade.getEcTradeStatus());
                sysOrder.setTradeCode(ecTrade.getEcTradeCode());
//                sysOrder.setPayMode("支付宝");//此处应该是通过tradetype映射相应的值 亦或者 可以先不做
                sysOrder.setPayMode(ecTrade.getPayMethod());
                //物流公司
                sysOrder.setLgstId(strLgstId);
                sysOrder.setLgstName(strLgstName);
                sysOrder.setLgstCode(strLgstCode);
                //仓库
                sysOrder.setStorId(strStorId);
                sysOrder.setStorName(strStorName);
                sysOrder.setStorCode(strStorCode);
                //收货信息
                sysOrder.setCons(ecTrade.getCons());
                sysOrder.setConsTel(ecTrade.getConsTel());
                sysOrder.setConsMobile(ecTrade.getConsMobile());
                sysOrder.setConsAddr(ecTrade.getConsAddr());
                sysOrder.setConsPostCode(ecTrade.getConsPostCode());

                sysOrder.setProvName(ecTrade.getProvName());
                sysOrder.setCityName(ecTrade.getCityName());
                sysOrder.setDistName(ecTrade.getDistName());

                if (StringUtils.isNotBlank(ecTrade.getAreaCoding())) {
                    if (StringUtils.isNumeric(ecTrade.getAreaCoding())) {
                        sysOrder.setAreaCoding(Integer.valueOf(ecTrade.getAreaCoding()));
                    } else {
                        sysOrder.setAreaCoding(0);
                    }
                } else {
                    sysOrder.setAreaCoding(0);
                }

                sysOrder.setLgstFee(ecTrade.getLgstFee());
                sysOrder.setServFee(ecTrade.getServFee());
                sysOrder.setPaidFee(ecTrade.getPaidFee());
                sysOrder.setPaidDate(ecTrade.getPaidTime());
                sysOrder.setCustRemark(ecTrade.getCustRemark());
                sysOrder.setSalesRemark(ecTrade.getSalesRemark());
                sysOrder.setRemark(ecTrade.getRemark());
                sysOrder.setConsignTime(ecTrade.getConsignTime());
                sysOrder.setInvoiceTitle(ecTrade.getCons());
                sysOrder.setJobStep("y".equals(strIsAutoMergeOrder) ? "a" : "c");
                sysOrder.setTbFlagCode(Long.valueOf(ecTrade.getSellerFlag()));

                //循环平台订单商品明细，赋值到系统订单商品明细
                List<EcOrder> ecOrderList = tradeOrderMap.get(ecTrade.getEcTradeId());
                EcOrder ecOrder = new EcOrder();
                List<SkuVO> itemSkuList = new ArrayList<SkuVO>();
                List<SkuGroup> skuGroupList = new ArrayList<SkuGroup>();
                SkuGroup skuGroup = new SkuGroup();
                String strIsGroup = "";
                List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();

                for (int orderIndex = 0; orderIndex < ecOrderList.size(); orderIndex++) {
                    SysOrderGoods sysOrderGoods = new SysOrderGoods();
                    ecOrder = ecOrderList.get(orderIndex);
                    itemSkuList = orderItemSkuMap.get(ecOrder.getEcItemCode() + "-" + ecOrder.getEcSkuCode());
                    if (itemSkuList != null && itemSkuList.size() > 0) {
                        strIsGroup = itemSkuList.get(0).getIsGroup();

                        //非组合商品
                        if ("n".equals(strIsGroup)) {
                            //取平台订单商品信息
                            sysOrderGoods.setOrderGoodsId(SnoGerUtil.getUUID());
                            sysOrderGoods.setOrderId(strOrderId);
                            sysOrderGoods.setQty(ecOrder.getQty());
                            sysOrderGoods.setPrice(ecOrder.getStanUnitPrice());
                            sysOrderGoods.setFactUnitPrice(ecOrder.getFactUnitPrice());
                            sysOrderGoods.setDivideOrderFee(ecOrder.getDivideOrderFee());
                            sysOrderGoods.setRemark(ecOrder.getRemark());
                            sysOrderGoods.setOid(ecOrder.getEcOid());
                            sysOrderGoods.setTradeCode(ecTrade.getEcTradeCode());
                            //取系统规格信息
                            sysOrderGoods.setSalePrice(itemSkuList.get(0).getSysSalePrice());
                            sysOrderGoods.setGoodsSkuCost(itemSkuList.get(0).getCostPrice());
                            sysOrderGoods.setIsVirt(itemSkuList.get(0).getIsVirt());
                            //取平台商品信息
                            sysOrderGoods.setEcSkuId(itemSkuList.get(0).getEcSkuId());
                            sysOrderGoods.setEcSkuCode(itemSkuList.get(0).getEcSkuCode());
                            sysOrderGoods.setEcSkuName(itemSkuList.get(0).getEcSkuName());
                            sysOrderGoods.setEcItemId(itemSkuList.get(0).getEcItemId());
                            sysOrderGoods.setEcItemCode(itemSkuList.get(0).getEcItemCode());
                            sysOrderGoods.setEcItemName(itemSkuList.get(0).getEcItemName());

                            sysOrderGoods.setEcSkuOuterCode(itemSkuList.get(0).getOuterCode());
                            sysOrderGoods.setEcItemOuterCode(itemSkuList.get(0).getItemOuterCode());

                            sysOrderGoods.setSkuId(itemSkuList.get(0).getSkuId());
                            sysOrderGoods.setSkuCode(itemSkuList.get(0).getSkuCode());
                            sysOrderGoods.setSkuName(itemSkuList.get(0).getSkuName());
                            sysOrderGoods.setGoodsId(itemSkuList.get(0).getGoodsId());
                            sysOrderGoods.setGoodsCode(itemSkuList.get(0).getGoodsCode());
                            sysOrderGoods.setGoodsName(itemSkuList.get(0).getGoodsName());
                            sysOrderGoodsList.add(sysOrderGoods);
                        } else {
                            //组合商品
                            if (itemSkuGrouprMap != null && itemSkuGrouprMap.size() > 0) {
                                skuGroupList = itemSkuGrouprMap.get(itemSkuList.get(0).getEcSkuId());
                                if (skuGroupList != null) {
                                    for (int skuGroupIndex = 0; skuGroupIndex < skuGroupList.size(); skuGroupIndex++) {
                                        sysOrderGoods = new SysOrderGoods();
                                        skuGroup = skuGroupList.get(skuGroupIndex);
                                        //取平台订单商品信息
                                        sysOrderGoods.setOrderGoodsId(SnoGerUtil.getUUID());
                                        sysOrderGoods.setOrderId(strOrderId);
                                        sysOrderGoods.setQty(ecOrder.getQty() * skuGroup.getNum());

                                        BigDecimal bdPrice = ecOrder.getStanUnitPrice().multiply(skuGroup.getPriceRatio())
                                                .divide(BigDecimal.valueOf(skuGroup.getNum()), 2, BigDecimal.ROUND_HALF_UP);//精确的除法运算。当发生除不尽的情况时，指定精度，以后的数字四舍五入
                                        sysOrderGoods.setPrice(bdPrice);//平台标准单价(吊牌价)
                                        BigDecimal bdFactUnitPrice = ecOrder.getFactUnitPrice().multiply(skuGroup.getPriceRatio())
                                                .divide(BigDecimal.valueOf(skuGroup.getNum()), 2, BigDecimal.ROUND_HALF_UP);
                                        sysOrderGoods.setFactUnitPrice(bdFactUnitPrice);//实际单价(拍单价)

                                        sysOrderGoods.setDivideOrderFee(ecOrder.getDivideOrderFee().multiply(skuGroup.getPriceRatio()));//实际支付金额
                                        sysOrderGoods.setRemark(ecOrder.getRemark());
                                        sysOrderGoods.setOid(ecOrder.getEcOid());
                                        sysOrderGoods.setTradeCode(ecTrade.getEcTradeCode());
                                        //取系统规格信息
                                        sysOrderGoods.setSalePrice(skuGroup.getSysSalePrice());
                                        sysOrderGoods.setGoodsSkuCost(skuGroup.getCostPrice());
                                        sysOrderGoods.setIsVirt(skuGroup.getIsVirt());
                                        //取平台商品信息
                                        sysOrderGoods.setEcSkuId(itemSkuList.get(0).getEcSkuId());
                                        sysOrderGoods.setEcSkuCode(itemSkuList.get(0).getEcSkuCode());
                                        sysOrderGoods.setEcSkuName(itemSkuList.get(0).getEcSkuName());
                                        sysOrderGoods.setEcItemId(itemSkuList.get(0).getEcItemId());
                                        sysOrderGoods.setEcItemCode(itemSkuList.get(0).getEcItemCode());
                                        sysOrderGoods.setEcItemName(itemSkuList.get(0).getEcItemName());

                                        sysOrderGoods.setEcSkuOuterCode(itemSkuList.get(0).getOuterCode());
                                        sysOrderGoods.setEcItemOuterCode(itemSkuList.get(0).getItemOuterCode());

                                        sysOrderGoods.setSkuId(skuGroup.getSkuId());
                                        sysOrderGoods.setSkuCode(skuGroup.getSkuCode());
                                        sysOrderGoods.setSkuName(skuGroup.getSkuName());
                                        sysOrderGoods.setGoodsId(skuGroup.getGoodsId());
                                        sysOrderGoods.setGoodsCode(skuGroup.getGoodsCode());
                                        sysOrderGoods.setGoodsName(skuGroup.getGoodsName());
                                        sysOrderGoodsList.add(sysOrderGoods);
                                    }
                                }
                            }
                        }
                    }
                }
                sysOrder.setSysOrderGoodsList(sysOrderGoodsList);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrder = null;
            logUtil.error(new DBLog(ecTrade.getEcTradeCode(), "系统订单自动下载", "跟踪日志", "系统订单赋值异常:" + ex.getMessage()));
        }
        return sysOrder;
    }

    /**
     * 系统订单插入数据库
     *
     * @param sysOrder
     * @return
     * @throws Exception
     */
    private int insertSysOrderInfo(SysOrder sysOrder) throws Exception {
        int iRes = 0;
        try {
            if (sysOrder != null) {
                //系统订单商品明细
                List<SysOrderGoods> sysOrderGoodsList = sysOrder.getSysOrderGoodsList();
                if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0)//保证系统订单一定有订单商品明细
                {
                    //系统订单主表信息插入数据库
                    iRes = sysOrderDAO.insertSelectiveSysOrder(sysOrder);
                    if (iRes > 0) {
                        //记录日志
                        logUtil.info(new DBLog(sysOrder.getOrderCode(), "系统订单自动下载", "", "系统订单自动下载成功"));
                        for (int sysOrderGoodsIndex = 0; sysOrderGoodsIndex < sysOrderGoodsList.size(); sysOrderGoodsIndex++) {
                            SysOrderGoods sysOrderGoods = sysOrderGoodsList.get(sysOrderGoodsIndex);
                            //系统订单商品明细信息插入数据库
                            sysOrderDAO.insertSelectiveSysOrderGoods(sysOrderGoods);
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(sysOrder.getTradeCode(), "系统订单自动下载", "跟踪日志", "系统订单插入数据库阶段异常:" + ex.getMessage()));
        }
        return iRes;
    }

    /**
     * 更新订单接口表插入系统表状态
     *
     * @param strEcTradeId
     * @param strEcTradeCode
     * @return
     * @throws Exception
     */
    private int updateEcTradeInsertStatus(String strEcTradeId, String strEcTradeCode) throws Exception {
        int iRes = 0;
        try {
            EcTrade ecTrade = new EcTrade();
            ecTrade.setEcTradeId(strEcTradeId);
            ecTrade.setIsInsert("y");
            iRes = orderService.updateByPrimaryKeySelectiveEcTrade(ecTrade);
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(strEcTradeCode, "系统订单自动下载", "跟踪日志", "更新平台订单进系统标识阶段异常:" + ex.getMessage()));
        }
        return iRes;
    }
}
